package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import custom.Quiz;
import custom.User;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("userOrQuiz");
		String word = request.getParameter("word");
		
		RequestDispatcher dispatch = null;
		if(type != null && word != null && word.length()>0 && type.equals("user")){

			if(User.checkUser(word, "")){
				dispatch = request.getRequestDispatcher("profile.jsp?name=" + word);
			}else{
				request.getSession().setAttribute("alert", "user \""+word+"\" doesnt exist");
				dispatch = request.getRequestDispatcher("home.jsp");
			}
		}else if(type != null && word != null && word.length()>0 && type.equals("quiz")){

			try {
				if(Quiz.checkQuiz(word)){
					dispatch = request.getRequestDispatcher("quizSummary.jsp?name=" + word);
				}else{
					request.getSession().setAttribute("alert", "Quiz \""+word+"\" doesnt exist");
					dispatch = request.getRequestDispatcher("home.jsp");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else{
			if(word.length() > 0)
				request.getSession().setAttribute("alert", "Something went wrong");
			dispatch = request.getRequestDispatcher("home.jsp");
		}
		dispatch.forward(request, response);
	}
}